/* Copyright (C) 2010 MoSync AB

This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License, version 2, as published by
the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
for more details.

You should have received a copy of the GNU General Public License
along with this program; see the file COPYING.  If not, write to the Free
Software Foundation, 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA.
*/

#ifndef XMLCONNECTION_H_
#define XMLCONNECTION_H_
#include <MAUtil/Connection.h>
#include <MAUtil/Downloader.h>
#include <MAUtil/String.h>
#include <MAUtil/Map.h>
#include <MTxml/MTXml.h>
#include <mastdlib.h>

using namespace MAUtil;
using namespace Mtx;

//Downloads XML from the Internet, providing authentication if necessary
//You need to provide an XmlListener class to it to process the XML

class XmlConnection : public HttpConnectionListener,
                      private MtxListener
{
  public:
    XmlConnection(String& username, String& password);
    XmlConnection();
    ~XmlConnection();

    void beginDownloading();
    void setURL(const char* queryURL);
    const char* getURL();
    void setHeader(String& header, String& value);
    void clearHeaders();
    void setData(String& data);

    //MtxListener
    void xcConnError(int code);

    void httpFinished(HttpConnection* conn, int code);
    void connRecvFinished(Connection* conn, int result);
    void connWriteFinished(Connection* conn, int result);

    bool isBusy();

    void setXmlListener(XmlListener* processor);
    XmlListener* getXmlListener();

    void close();
  protected:
    bool mIsDownloading;
    bool mUserData;
    MAHandle mData;
    char mBuffer[1024];
    char* mPtr;
    bool mIsRedirecting;
    Context mContext;

  private:
    String mUsername;
    String mPassword;
    String mUrl;

    String mCommandData;
    Map<String, String> mHeaders;
    HttpConnection* mConn;
    bool hasError;
    bool mIsBusy;
    bool mIsReading;

    XmlListener* mProcessor;

    void mtxDataRemains(const char* data, int len);
    void stop();
    int process(char* data);
};

#endif /* TWITTERCONNECTION_H_ */
